<template>
    <div>
        <!-- 面包屑导航区 -->
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>商品管理</el-breadcrumb-item>
                <el-breadcrumb-item>参数列表</el-breadcrumb-item>
            </el-breadcrumb>


        <el-card>
            <!-- 提示区域 -->
            <el-row>
                <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" show-icon :closable="false"></el-alert>
            </el-row>

            <!-- 选择商品分类区域 -->
            <el-row>
                <el-col>
                    选择商品分类：
                    <el-cascader
                        clearable
                        :options="catelist"
                        :props="cateProps"
                        v-model="selectedCateKeys"
                        @change="handleChange">
                    </el-cascader>

                </el-col>
            </el-row>

        <!-- Tabs页签区域 -->
        <el-tabs v-model="activeName" @tab-click="handleTabsClick">
            <!-- 添加 动态参数  -->
            <el-tab-pane label="动态参数" name="many">
                <el-button type="primary" size="mini" :disabled="isBtnDisable" @click="addParamsVisbleBtn">添加参数</el-button>

                <el-table :data="manyTableData" border stripe>
                     <!--  展开行  -->
                    <el-table-column type="expand">
                        <template slot-scope="scope">
                            <el-tag
                                v-for="(item,index) in scope.row.attr_vals"
                                :key="index"
                                closable
                                @close="handleClose(i,scope.row)"
                            >
                                {{item}}
                            </el-tag>
                            <el-input
                                class="input-new-tag"
                                v-if="scope.row.inputVisible"
                                v-model="scope.row.inputValue"
                                ref="saveTagInput"
                                size="small"
                                @keyup.enter.native="handleInputConfirm(scope.row)"
                                @blur="handleInputConfirm(scope.row)"
                            >
                            </el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column type="index" label="#"></el-table-column>
                    <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button type="primary" size="mini" class="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                            <el-button type="danger" size="mini" class="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>


            <!-- 添加 静态属性  -->
            <el-tab-pane label="静态属性" name="only">
                <el-button type="primary" size="mini" :disabled="isBtnDisable" @click="addParamsVisbleBtn">添加属性</el-button>

                <el-table :data="onlyTableData" border stripe>
                     <!--  展开行  -->
                    <el-table-column type="expand">
                        <template slot-scope="scope">
                            <el-tag
                                v-for="(item,index) in scope.row.attr_vals"
                                :key="index"
                                closable
                                @close="handleClose(i,scope.row)"
                            >
                                {{item}}
                            </el-tag>
                            <el-input
                                class="input-new-tag"
                                v-if="scope.row.inputVisible"
                                v-model="scope.row.inputValue"
                                ref="saveTagInput"
                                size="small"
                                @keyup.enter.native="handleInputConfirm(scope.row)"
                                @blur="handleInputConfirm(scope.row)"
                            >
                            </el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column type="index" label="#"></el-table-column>
                    <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button type="primary" size="mini" class="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                            <el-button type="danger" size="mini" class="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

            </el-tab-pane>

        </el-tabs>

        </el-card>

    <!-- 添加参数和属性提示框  -->
    <el-dialog
        :title="'添加'+titleText"
        :visible.sync="addParamsVisble"
        width="50%"
        @close="addParamsClosed"
    >
    <!-- 添加参数和属性 表单  -->
    <el-form
        :model="addParamsForm"
        :rules="addParamsRules"
        ref="addParamsRef"
        label-width="100px"
        >
        <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
    </el-form>


    <!-- 添加参数和属性 确定和取消  -->
    <span slot="footer">
        <el-button @click="addParamsVisble = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
    </span>
    </el-dialog>

    <!-- 修改参数和属性提示框  -->
    <el-dialog
        :title="'修改'+titleText"
        :visible.sync="editParamsVisble"
        width="50%"
        @close="editParamsClosed"
    >
    <!-- 添加参数和属性 表单  -->
    <el-form
        :model="editParamsForm"
        :rules="editParamsRules"
        ref="editParamsRef"
        label-width="100px"
        >
        <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
    </el-form>


    <!-- 添加参数和属性 确定和取消  -->
    <span slot="footer">
        <el-button @click="editParamsVisble = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
    </span>
    </el-dialog>

    </div>
</template>

<script>
export default {
name:'Params',
created(){
    this.getCatelist()
},
data() {
    return {
        catelist:[],
        cateProps: {
            expandTrigger:'hover',
            value: 'cat_id',
            label: 'cat_name',
            children: 'children',
        },
        selectedCateKeys:[],
        //被激活页签的名称
        activeName:'many',
        manyTableData:[],
        onlyTableData:[],
        addParamsVisble:false,
        addParamsForm:{
            attr_name:''
        },
        addParamsRules:{
            attr_name:[
                {required:true,message:'请输入参数名称',trigger:'blur'}
            ]
        },


        editParamsVisble:false,
        editParamsForm:{
        },
        editParamsRules:{
            attr_name:[
                {required:true,message:'请输入参数名称',trigger:'blur'}
            ]
        }

    }
},
computed:{
    //如果按钮需要被禁用则返回true 否则返回false
    isBtnDisable(){
        if (this.selectedCateKeys.length !==3 ) {
            return true
        } else {
            return false
        }
    },
    //当前选中的 三级分类的id
    cateId(){
        if(this.selectedCateKeys.length ===3) {
            return this.selectedCateKeys[2]

        }
        return null
    },
    titleText(){
        if (this.activeName === 'many') {
            return '动态参数'
        }
        return '静态属性'
    }
},
methods:{
    async getCatelist(){
        const {data:res} = await this.$http.get('categories')
        if(res.meta.status !== 200) return this.$message.error('获取商品权限列表失败')
        this.catelist = res.data
    },
    handleChange(){
        this.getParamsData()

    },
    async getParamsData(){
        if(this.selectedCateKeys.length !== 3 ){
            this.selectedCateKeys = []
            this.manyTableData=[]
            this.onlyTableData=[]
            return this.$message.error('只允许为第三级分类设置相关参数')
        }

        const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes`,{params:{sel:this.activeName}})
        if(res.meta.status !== 200) return this.$message.error('获取参数列表失败')
        if (this.activeName === 'many') {
            res.data.forEach(item => {
                item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
                //控制文本框的显示与隐藏
                item.inputVisible = false
                //文本框中要输入的值
                item.inputValue = ''
            });
            this.manyTableData = res.data
        } else {
            res.data.forEach(item => {
                item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
                //控制文本框的显示与隐藏
                item.inputVisible = false
                //文本框中要输入的值
                item.inputValue = ''
            });

            this.onlyTableData = res.data
        }
    },
    //tabs页签点击事件
    handleTabsClick(){
        this.getParamsData()
    },
    addParamsVisbleBtn(){
        this.addParamsVisble = true
    },
    addParamsClosed(){
        this.$refs.addParamsRef.resetFields()
    },
    addParams(){
        this.$refs.addParamsRef.validate(async valid => {
            if (!valid) return
            const {data:res} = await this.$http.post(`categories/${this.cateId}/attributes`,{
                attr_name: this.addParamsForm.attr_name,
                attr_sel: this.activeName,

            })
            if(res.meta.status !== 201) return this.$message.error("添加"+this.titleText+"失败！")
            this.$message.success("添加"+this.titleText+"成功！")
            this.addParamsVisble = false
            this.getParamsData()
        })
    },
    editParamsClosed(){
        this.$refs.editParamsRef.resetFields()
    },
    editParams(){
         this.$refs.editParamsRef.validate(async valid => {
            if (!valid) return
            const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`,
            {
                attr_name: this.editParamsForm.attr_name,
                attr_sel: this.activeName,
            })
            if(res.meta.status !== 200) return this.$message.error("修改"+this.titleText+"失败！")
            this.$message.success("修改"+this.titleText+"成功！")
            this.getParamsData()
            this.editParamsVisble = false
        })
    },
    async showEditDialog(attr_id){
        const {data:res} =
        await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`,{ params: {attr_sel: this.activeName}})
        if(res.meta.status !== 200) return this.$message.error('获取参数信息失败')
        this.editParamsForm = res.data
        this.editParamsVisble = true
    },
    async removeParams(attr_id) {
        const confirm = await this.$confirm('此操作将永久删除该参数, 是否继续?', '删除参数', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        if(confirm !== "confirm"){
            return this.$message.info("已取消删除！")
        }
        const {data:res} = await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)
        if(res.meta.status !== 200) return this.$message.error('删除参数失败')
        this.$message.success('删除参数成功')
        this.getParamsData()
    },
     async saveAttrVals(row){
        const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
    })
     if(res.meta.status !== 200) return this.$message.error('添加参数项失败')
        this.$message.success('添加参数项成功')
    },
    //文本框失去焦点或者按下enter
    async handleInputConfirm(row){
        if (row.inputValue.trim().length===0) {
            row.inputValue = ''
            row.inputVisible = false
            return
        }
        //如果没有 返回 说明有值在 需要做后续处理
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = ''
        row.inputVisible = false
        this.saveAttrVals(row)
    },
    showInput(row){
        row.inputVisible=true
        this.$nextTick(_ =>{
            this.$refs.saveTagInput.$refs.input.focus()
        })
    },
    //删除对应的参数可选项
    handleClose(i,row){
        row.attr_vals.splice(i,1)
        this.saveAttrVals(row)
    },

}
}
</script>

<style lang="less" scoped>
.el-tag {
    margin: 10px;
}
.input-new-tag {
    width: 100px;
}
</style>